﻿//-----------------------------------------------------------------------
// <copyright>
// This file is subject to the terms and conditions of the Microsoft Public License (MS-PL).
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details.
// </copyright>
//----------------------------------------------------------------------- 
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;

namespace Fulcrum.ViewModelGenerator
{
    public class ViewModelCollectionXmlConfig : IViewModelCollectionConfig
    {
        public IList<IViewModelConfiguration> ViewModels { get; private set; }
        public string Company { get; private set; }
        public string Copyright { get; private set; }
        public string Namespace { get; private set; }

        public ViewModelCollectionXmlConfig(XDocument xml)
        {
            if (null == xml)
            {
                throw new ArgumentNullException("xml");
            }

            this.ViewModels = new List<IViewModelConfiguration>();

            this.Parse(xml);
        }

        private void Parse(XDocument xml)
        {
            var viewModelsXml = this.GetViewModelsXml(xml);
            this.ParseGlobalSettings(viewModelsXml);
            this.ParseViewModels(viewModelsXml);
        }

        private XElement GetViewModelsXml(XDocument xml)
        {
            var viewModelsXml = xml.Element("ViewModels");
            if (null == viewModelsXml)
            {
                throw new ArgumentException("Xml document does not not contain a 'ViewModels' node.", "xml");
            }

            return viewModelsXml;
        }

        private void ParseGlobalSettings(XElement xml)
        {
            Debug.Assert(null != xml && xml.Name == "ViewModels");

            this.Company = (string)xml.RequiredAttribute("Company");
            this.Copyright = (string)xml.RequiredAttribute("Copyright");
            this.Namespace = (string)xml.OptionalAttribute("Namespace", String.Empty);
        }

        private void ParseViewModels(XElement xml)
        {
            Debug.Assert(null != xml && xml.Name == "ViewModels" && null != this.ViewModels);

            var viewModels = from vm in xml.Elements("ViewModel")
                             select new ViewModelXmlConfiguration(vm, this.Namespace);

            viewModels.ToList().ForEach(vm => this.ViewModels.Add(vm));
        }
    }
}
